package com.vcaresolution.logistic.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ApplicationLoginFilter implements Filter{

	private FilterConfig filterConfig = null;
	
	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {

		final HttpServletRequest request = (HttpServletRequest) req;
		final HttpServletResponse response = (HttpServletResponse) res;
		final HttpSession session = request.getSession();
		
		String requestedURL = request.getRequestURL().toString();
		
		final Object userProfile = session.getAttribute(ApplicationConstants.USERPROFILE_SESSION_OBJECT);
		final String contextPath = filterConfig.getServletContext().getContextPath()+ApplicationConstants.URL_SEPERATOR;
		
		boolean continueChaining = false;
		if( requestedURL != null ){
			if( requestedURL.endsWith(contextPath)
					|| requestedURL.endsWith("Index.jsp")  
					|| requestedURL.endsWith("Login.jsp") 
					|| requestedURL.endsWith("Login")
					|| requestedURL.endsWith(".js")
					|| requestedURL.endsWith(".css")
					|| userProfile != null ){
				continueChaining = true;
			}
		}
		
		if( continueChaining ){
			chain.doFilter(req, res);
		}
		else{
			response.sendRedirect(contextPath);
		}
		
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		this.filterConfig = config;
	}

}
